# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
  include CalendarHelper
  # Returns a link tag with the specified +title+ that will invoke a popup
  # window with the supplied +window_title+ and using the javascript window
  # options passed in +window_options+. +options+ is a hash identical to that
  # used by ActionView::Helpers::UrlHelper#url_for. i.e.:
  #   popup_link('Click Me', 'click_me', 'width=400,height=400,scrollbars',
  #              :controller => 'foo', :action => 'index')
  # would produce something like:
  #   <a href="/foo/index" onclick="window.open('/foo/index','click_me',
  #     'width=400,height=400,scrollbars');return false;">Click Me</a>
  def popup_link(title,window_title,window_options,options)
    xml = Builder::XmlMarkup.new
    link = url_for(options)
    xml.a(title, :href => link,
          :onclick => "window.open('#{link}','#{window_title}'," +
                      "'#{window_options}');return false;")
  end
  # Displays a textual representation of +date+ in the long format (i.e.:
  # "Tuesday March 22, 2005")
  def long_date(date)
    "#{Date::DAYNAMES[date.wday]} #{Date::MONTHNAMES[date.mon]} #{date.day}, " +
    "#{date.year}"
  end

  # Displays a textual representation of +date+ in the abbreviated format (i.e.:
  # "Tue Mar 22, 05")
  def short_date(date)
    "#{Date::ABBR_DAYNAMES[date.wday]} #{Date::ABBR_MONTHNAMES[date.mon]} " +
    "#{date.day}, '#{date.year.to_s.slice(-2,2)}"
  end

  # Displays the numeric representation of +date+ (i.e.: "3/22/2005")
  def numeric_date(date)
    "#{date.mon}/#{date.day}/#{date.year}"
  end
  
  def date_picker_field(object, method)
    obj = instance_eval("@#{object}")
    value = obj.send(method)
    display_value = value.respond_to?(:strftime) ? value.strftime('%d %b %Y') : value.to_s
    display_value = '[ choose date ]' if display_value.blank?

    out = hidden_field(object, method)
    out << content_tag('a', display_value, :href => '#',
        :id => "_#{object}_#{method}_link", :class => '_demo_link',
        :onclick => "DatePicker.toggleDatePicker('#{object}_#{method}'); return false;")
    out << tag('div', :class => 'date_picker', :style => 'display: none',
                      :id => "_#{object}_#{method}_calendar")
    if obj.respond_to?(:errors) and obj.errors.on(method) then
      ActionView::Base.field_error_proc.call(out, nil) # What should I pass ?
    else
      out
    end
  end
    
end
